﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using YeqianFramework.config;
using YeqianFramework.common;
using System.Reflection;
using System.IO;
using System;
using Assets.Scripts.Config;

namespace Assets.Scripts.Editor
{
	[CustomEditor(typeof(ConfigScriptableObject), true)]
	public class ConfigScriptableObjEditor : UnityEditor.Editor
	{
		public SerializedObject mObj;
		public ConfigScriptableObject configObj;

		public void OnEnable()
		{
			try
			{
				mObj = new SerializedObject(target);
			}
			catch (ArgumentException) { }
			configObj = target as ConfigScriptableObject;

			if (configObj.SavePath == null || configObj.SavePath.Equals(string.Empty)) configObj.SavePath = "F://";

			//SavePathProp = configObj.GetType().GetField("保存路径");
			//tempSavePath = SavePathProp.GetValue(target).ToString();
		}
		//string tempSavePath;
		public override void OnInspectorGUI()//决定组件面板应该怎么绘制面板
		{
			this.mObj.Update();//更新对象

			base.DrawDefaultInspector();//绘制默认的东西


			this.mObj.ApplyModifiedProperties();//更改数据

			EditorGUILayout.Space();
			EditorGUILayout.Space();

			EditorGUILayout.BeginHorizontal();
			if (GUILayout.Button("生成XML"))
			{

				XmlHelper.Object2Xml(configObj.SavePath, configObj.GetType().GetField("config").GetValue(configObj));
				Debug.Log(string.Format("<color=red>Ciallo～(∠ • ω< )╭☆</color> {0} 创建成功", Path.GetFileName(configObj.SavePath)));
			}
			if (GUILayout.Button("读取XML"))
			{
				//读取出来的配置表类型
				Config.Config temp = (Config.Config)XmlHelper.Xml2Object(configObj.SavePath, configObj.GetType().GetField("config").FieldType);
				Type type = temp.GetType();
				FieldInfo[] fieldInfos = type.GetFields();
				foreach (var item in fieldInfos)
				{
					item.SetValue(configObj.GetType().GetField("config").GetValue(configObj), item.GetValue(temp));
				}
				Debug.Log(string.Format("<color=red>Ciallo～(∠ • ω< )╭☆</color> {0} 读取成功", Path.GetFileName(configObj.SavePath)));
			}

			EditorGUILayout.EndHorizontal();
		}
	}
}
